package lumis.service.portalmanagement.audit;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.audit.AuditManager;
import lumis.portal.manager.ManagerFactoryInternal;
import lumis.util.XmlUtil;

/**
 * Perform actions over the Audit types like enable and disable them.
 *
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class AuditProcessActionHandler extends ProcessActionHandler<Source>
{
	/**
	 * Parameter name for audit entry type id.
	 */
	private static final String PARAMETER_TYPE_ID = "auditEntryTypeId";
	
	/**
	 * Enum with the possible actions for this process action handler.
	 *
	 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
	 * @since 6.0.0
	 */
	enum AuditActionType
	{
		/**
		 * Enable an audit type.
		 */
		ENABLE_TYPE,
		/**
		 * Disable an audit type.
		 */
		DISABLE_TYPE;
	}
	
	public void processAction() throws PortalException
	{
		AuditActionType id = Enum.valueOf(AuditActionType.class, XmlUtil.readAttributeString("id", processActionNode));
		String[] typeIdArray = (String[]) getParameter(PARAMETER_TYPE_ID);

		switch (id)
		{
			case ENABLE_TYPE:
			{
				setAuditTypeEnabledState(true, typeIdArray);
				break;
			}
			case DISABLE_TYPE:
			{
				setAuditTypeEnabledState(false, typeIdArray);
				break;
			}
		}
		
		addDefaultResponse();
	}
	
	/**
	 * Updates enable state of the given type.
	 * @param enabled			true to enable or false to disable.
	 * @param typeIdArray		array of audit type id's.
	 * @throws PortalException	if an error occur updating enable state.
	 * @since 6.0.0
	 */
	private void setAuditTypeEnabledState(boolean enabled, String[] typeIdArray) throws PortalException
	{		
		AuditManager auditManager = (AuditManager) ManagerFactoryInternal.getAuditManager();
		
		if ((typeIdArray != null) && (typeIdArray.length > 0))
		{
			for (String typeId: typeIdArray)
			{
				if (enabled)
				{
					auditManager.enableType(typeId);
				}
				else
				{
					auditManager.disableType(typeId);
				}
			}
		}
		else
		{
			throw new PortalException("STR_NO_ITEM_SELECTED", getResource());	
		}
	}
}